package com.zm.damai.damaiindex.web;

import com.zm.damai.damaiindex.web.feign.OtherAction;
import com.zm.damai.entity.DmProduct;
import com.zm.damai.entity.SecKillOrder;
import com.zm.damaicommon.Result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("secKill")
public class SecKillDo {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    OtherAction otherAction;

    @Autowired
    TaskScheduler taskScheduler;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @RequestMapping("aaa")
    List<DmProduct> aaa(){
        System.out.println("sssssssssssssssssssss");
        System.out.println(otherAction.querySecKillProduct());
//        List<DmProduct> secKillProducts = otherAction.querySecKillProduct();
        System.out.println("bbbbbbbbbbbbbbbbbbbbb");
//        return secKillProducts;
        return null;
    }

    @RequestMapping("start")
    public Result start(){
        //判断
        if (redisTemplate.hasKey("SecKillInfo")) {
            return new Result(-1,"秒杀活动已经开始",null);
        }
        //查询10个库存最多的商品，扣减1000个库存作为商品
        System.out.println("sssssssssssssssssssss");
        List<DmProduct> secKillProducts = otherAction.querySecKillProduct();
        System.out.println("secKillProducts.size() = " + secKillProducts.size());
        //保存数据到redis中
        SecKillInfo secKillInfo = new SecKillInfo();
        secKillInfo.setProducts(secKillProducts);
        secKillInfo.setBegin(new Date());
        secKillInfo.setEnd(new Date(secKillInfo.getBegin().getTime() + 1000*60*5));
        redisTemplate.opsForValue().set("SecKillInfo", secKillInfo);

        //将商品的库存单独保存
        for (DmProduct product : secKillInfo.getProducts()) {
            redisTemplate.opsForValue().set("secKill:" + product.getId(), product.getStore());
        }

        //加入延时任务
        taskScheduler.schedule(()->{
            finish();
        },secKillInfo.end);
        return new Result(1,"秒杀活动开始！",null);
    }

    public void finish(){
        System.out.println("==================秒杀活动结束=====================");
        SecKillInfo secKillInfo = (SecKillInfo) redisTemplate.opsForValue().get("SecKillInfo");
        //TODO 此处代码待优化
        otherAction.updateSeckillProduct(secKillInfo.getProducts());
        redisTemplate.delete("SecKillInfo");
    }

    @RequestMapping("commit")
    public Result commit(int pid , int uid, @RequestParam(defaultValue = "1") int cnt){
        //验证
        if (redisTemplate.hasKey("secKill:" + pid) == false) {
            return new Result(-1,"该商品不是秒杀商品",null);
        }
        // TODO 判断用户是否秒杀过该商品
        //减库存
        Integer store = (Integer) redisTemplate.opsForValue().get("secKill:" + pid);
        redisTemplate.opsForValue().set("secKill:" + pid,store - cnt);
        //订单生成消息 =》 消息队列
        SecKillOrder order = new SecKillOrder();
        order.setPid(pid);
        order.setUid(uid);
        order.setCnt(cnt);
        rabbitTemplate.convertAndSend("secKillQueue",order);
        return new Result(1,"商品秒杀成功",null);
    }

    @RequestMapping("query")
    public Result query(){
        if (redisTemplate.hasKey("SecKillInfo") == false) {
            return new Result(-1,"秒杀活动未开始",null);
        }
        SecKillInfo secKillInfo = (SecKillInfo) redisTemplate.opsForValue().get("SecKillInfo");
        return new Result(1,"秒杀活动进行中",secKillInfo);
    }

    @PostConstruct
    void init(){
        redisTemplate.delete("SecKillInfo");
        Set keys = redisTemplate.keys("SecKill:*");
        for (Object key : keys) {
            redisTemplate.delete(key);
        }
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class SecKillInfo implements java.io.Serializable{
    List<DmProduct> products;
    Date begin;
    Date end;
}
